package com.sx.micowell.framework.tools;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;


import com.example.mvvm.until.LogUtils;
import com.example.mvvm.until.Utils;

import org.jetbrains.annotations.NotNull;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;

import kotlin.jvm.internal.Intrinsics;

/**
 * @author: YY
 * @time: 2021/6/1
 * @describe 文件操作 工具类
 */
public class FileUtils {

    private final static String PATTERN = "yyyyMMddHHmmss";
    private static final String SEPARATOR = File.separator;
    private static final String EXTERNAL_ROOT = "factoryOnline";

    private static final String EXTERNAL_STORAGE = Environment.getExternalStorageDirectory().getAbsolutePath() + SEPARATOR + EXTERNAL_ROOT;

    private static final String IMAGE = "image";
    private static final String PARENT_PATH = SEPARATOR + "jyk" + SEPARATOR;

    public static ArrayList<String> getAllFilePath(String filePath) {
        File file = new File(filePath);
        File[] subFile = file.listFiles();
        ArrayList<String> fileList = new ArrayList<>();

        for (int iFileLength = 0; iFileLength < subFile.length; iFileLength++) {
            // 判断是否为文件夹
            if (!subFile[iFileLength].isDirectory()) {
                String filename = subFile[iFileLength].getAbsolutePath();
                fileList.add(filename);
            }
        }
        return fileList;
    }

    /**
     * 关闭IO
     *
     * @param closeables closeable
     */
    public static void closeIO(Closeable... closeables) {
        if (closeables == null) {
            return;
        }
        try {
            for (Closeable closeable : closeables) {
                if (closeable != null) {
                    closeable.close();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static File createTempImage(/*Context context*/) {
        String timeStamp = new SimpleDateFormat(PATTERN, Locale.CHINA).format(new Date());
        File file = new File(getImagePath(), timeStamp + ".jpg");
        try {
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }


    public static String getImagePath() {
        return getStoreExternalPath(IMAGE) + PARENT_PATH;
    }

    private static String getStoreExternalPath(String folder) {
        File file = new File(EXTERNAL_STORAGE + SEPARATOR + folder);
        if (!file.exists()) {
            file.mkdirs();
        }
        return file.getAbsolutePath();
    }

    /**
     * 获取文件夹大小
     * @param dir
     * @return
     */
    public static final long getDirSize(File dir) {
        Intrinsics.checkParameterIsNotNull(dir, "dir");
        if (!dir.isDirectory()) {
            return 0L;
        } else {
            long dirSize = 0L;
            File[] var10000 = dir.listFiles();
            if (var10000 != null) {
                File[] files = var10000;
                File[] var6 = files;
                int var7 = files.length;

                for(int var5 = 0; var5 < var7; ++var5) {
                    File file = var6[var5];
                    Intrinsics.checkExpressionValueIsNotNull(file, "file");
                    if (file.isFile()) {
                        dirSize += file.length();
                    } else if (file.isDirectory()) {
                        dirSize += file.length();
                        dirSize += getDirSize(file);
                    }
                }

                return dirSize;
            } else {
                return 0L;
            }
        }
    }

    /**
     * 获取包名下的数据库文件
     * @param context
     * @return
     */
    public static File getDatabaseDir(@NotNull Context context) {
        Intrinsics.checkParameterIsNotNull(context, "context");
        return new File("/data/data/" + context.getPackageName() + "/databases");
    }

    /**
     * 转换文件大小
     * @param fileS
     * @return
     */
    public static String formatFileSize(long fileS) {
        DecimalFormat df = new DecimalFormat("0.00");
        String fileSizeString = "";
        if (fileS < (long)1024) {
            fileSizeString = df.format((double)fileS) + "B";
        } else if (fileS < (long)1048576) {
            fileSizeString = df.format((double)fileS / (double)1024) + "KB";
        } else if (fileS < (long)1073741824) {
            fileSizeString = df.format((double)fileS / (double)1048576) + "MB";
        } else {
            fileSizeString = df.format((double)fileS / (double)1073741824) + "G";
        }
        LogUtils.d("formatFileSize: "+fileSizeString);
        return fileSizeString;
    }

    public static String getRealPathFromUri(Uri contentUri) {
        Cursor cursor = null;
        try {
            String[] proj = { MediaStore.Images.Media.DATA };
            cursor = Utils.getContext().getContentResolver().query(contentUri, proj, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }

    /**
     *  根据Uri获取文件真实地址
     */
    public static String getRealFilePath(Context context, Uri uri) {
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String realPath = null;
        if (scheme == null)
            realPath = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            realPath = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri,
                    new String[]{MediaStore.Images.ImageColumns.DATA},
                    null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        realPath = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        if (TextUtils.isEmpty(realPath)) {
            if (uri != null) {
                String uriString = uri.toString();
                int index = uriString.lastIndexOf("/");
                String imageName = uriString.substring(index);
                File storageDir;

                storageDir = Environment.getExternalStoragePublicDirectory(
                        Environment.DIRECTORY_PICTURES);
                File file = new File(storageDir, imageName);
                if (file.exists()) {
                    realPath = file.getAbsolutePath();
                } else {
                    storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
                    File file1 = new File(storageDir, imageName);
                    realPath = file1.getAbsolutePath();
                }
            }
        }
        return realPath;
    }
}
